package fragment;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.ArrayBlockingQueue;

import message.Message;

public class MessageHandler extends QuasiComponentMessageHandler {

	private ArrayBlockingQueue<message.Message> messageBox = new ArrayBlockingQueue<message.Message>(999);
	
	@Override
	public void send(message.Message message) {
		try {
			messageBox.put(message);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public PersistentStateMessageHandler getPersistentState() {
		return new PersistentStateMessageHandler(new ArrayList<message.Message>(messageBox));
	}

	@Override
	public void setPersistentState(PersistentStateMessageHandler state) {
		messageBox = new ArrayBlockingQueue<message.Message>(10, false, state.messageBox);
		System.out.println("Message Component started with "+messageBox.size()+ " messages");
	}


	@Override
	public Vector<Message> receive() {
		Vector<Message> res= new Vector<Message>();
		for(int i=0; i<messageBox.size();i++)
			res.add(messageBox.poll());
		return res;
	}

	@Override
	public void start() {
		// TODO Auto-generated method stub
		
	}


}
